package org.ling.xuan.dao;

import cn.hutool.core.util.StrUtil;
import org.ling.xuan.config.DbConfig;
import org.ling.xuan.entity.mo.LocalAdd;
import org.ling.xuan.entity.row.LocalAddRowMapper;
import org.ling.xuan.util.LxOptional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class LocalAddDao {
    public static LocalAdd getCur() {
        String sql = "SELECT * FROM local_add WHERE cur = TRUE and deleted = FALSE ";
        List<LocalAdd> list = DbConfig.getJdbcTemplate().query(sql, LocalAddRowMapper.INSTANCE);
        if (!list.isEmpty()) {
            return list.get(0); // Return the first result if it exists
        } else {
            insertNewAdd();
            return getCur(); // Return null if the list is empty
        }
    }

    public static String getCurId() {
        String sql = "SELECT id FROM local_add WHERE cur = TRUE and deleted = FALSE ";
        List<String> idList = DbConfig.getJdbcTemplate().query(sql, (rs, rowNum) -> rs.getString("id"));
        if (!idList.isEmpty()) {
            return idList.get(0); // Return the first result if it exists
        } else {
            return insertNewAdd(); // Return null if the list is empty
        }
    }

    public static void updateWithFile(LocalAdd localAdd) {
        DbConfig.getTransactionTemplate().execute(status -> {
            try {
                String sql = "UPDATE local_add SET " +
                        "modify_id = ?,bank_code=?,modify_version=?, add_msg = ?, send = ?,commited=?,require_bank = ?, " +
                        "requirement_id = ?, requirement_des = ?, mark_file_ids = ?, cur = ?, deleted = ?,skip_sql = ?,deploy_type = ? " +
                        "WHERE id = ?";
                DbConfig.getJdbcTemplate().update(sql, localAdd.getModifyId(), localAdd.getBankCode(), localAdd.getModifyVersion(),
                        localAdd.getAddMsg(), false, false, localAdd.getRequireBank(),
                        localAdd.getRequirementId(), localAdd.getRequirementDes(),
                        String.join(",", localAdd.getMarkFileIds()), false, false,localAdd.isSkipSql(),localAdd.getDeployType(),
                        localAdd.getId());
                MarkFileDao.updateAddId(localAdd.getId(), localAdd.getMarkFileIds());
                if (StrUtil.isBlank(getCurId())) {
                    insertNewAdd();
                }
                status.flush();
            } catch (Exception e) {
                // 发生异常，手动回滚事务
                status.setRollbackOnly();
                throw e;
            }
            return true;
        });

    }

    private static String insertNewAdd() {
        String id = StrUtil.uuid();
        String sql2 = "INSERT INTO local_add (id, modify_id,bank_code,modify_version, ctd_time, add_msg, send,commited, require_bank, requirement_id, requirement_des, mark_file_ids, cur, deleted,skip_sql,deploy_type) " +
                "VALUES (?, ?,?,?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?,?,?)";
        DbConfig.getJdbcTemplate().update(sql2, id, "", "", "", new Date(),
                "", false, false, "",
                "", "",
                "", true, false,false,"req");
        return id;
    }

    public static void updateCurAddSimple(LocalAdd localAdd) {
        String curId = "";
        if (StrUtil.isBlank(localAdd.getId())) {
            curId = getCurId();
        } else {
            curId = localAdd.getId();
        }
        String sql = "UPDATE local_add SET " +
                "modify_id = ?,bank_code = ?,modify_version = ?, add_msg = ?, send = ?, commited =?,require_bank = ?, " +
                "requirement_id = ?, requirement_des = ?, mark_file_ids = ?, cur = ?, deleted = ?,skip_sql=?,deploy_type=? " +
                "WHERE id = ?";
        DbConfig.getJdbcTemplate().update(sql, localAdd.getModifyId(), localAdd.getBankCode(), localAdd.getModifyVersion(),
                localAdd.getAddMsg(), false, false, localAdd.getRequireBank(),
                localAdd.getRequirementId(), localAdd.getRequirementDes(),
                String.join(",", LxOptional.of(localAdd.getMarkFileIds()).orElse(new ArrayList<>())), true, false,localAdd.isSkipSql(),localAdd.getDeployType(),
                curId);
    }

    public static boolean canLocalAdd() {
        return MarkFileDao.hasUnMarkFiles();
    }

    public static List<LocalAdd> list() {
        String sql = "SELECT * FROM local_add order by ctd_time desc ";
        return DbConfig.getJdbcTemplate().query(sql, LocalAddRowMapper.INSTANCE);
    }

    public static LocalAdd getById(String id) {
        String sql = "SELECT * FROM local_add WHERE id = ? and deleted = FALSE ";
        List<LocalAdd> list = DbConfig.getJdbcTemplate().query(sql, LocalAddRowMapper.INSTANCE, id);
        if (!list.isEmpty()) {
            return list.get(0); // Return the first result if it exists
        } else {
            insertNewAdd();
            return getCur(); // Return null if the list is empty
        }
    }

    public static void delete(String id) {
        String sql = "delete FROM local_add where id = ?";
        DbConfig.getJdbcTemplate().update(sql, id);
    }

    public static void svnCommitSuccess(String id) {
        String sql = "update local_add set commited = true where id = ?";
        DbConfig.getJdbcTemplate().update(sql, id);
    }

    public static void sended(String id) {
        String sql = "update local_add set send = true where id = ?";
        DbConfig.getJdbcTemplate().update(sql, id);
    }

    public static void initSendAndCommitStatus(String id) {
        String sql = "update local_add set send = false, commited = false where id = ?";
        DbConfig.getJdbcTemplate().update(sql, id);
    }

    public static List<LocalAdd> searchByCondition(String mod,String msg, String req, String fn, String bk) {
        String sql = "select * from local_add where 1=1 ";
        if(StrUtil.isNotBlank(mod)){
            sql +=" and modify_id like '%"+mod+"%' ";
        }
        if(StrUtil.isNotBlank(msg)){
            sql +=" and add_msg like '%"+msg+"%' ";
        }
        if(StrUtil.isNotBlank(req)){
            sql +=" and requirement_id like '%"+req+"%' ";
        }
        if(StrUtil.isNotBlank(bk)){
            sql +=" and require_bank like '%"+bk+"%' ";
        }
        if(StrUtil.isNotBlank(fn)){
            sql +=" and id in (select add_id from mark_file where file_name like '%"+fn+"%')";
        }
        sql += " order by ctd_time desc ";
        return DbConfig.getJdbcTemplate().query(sql, LocalAddRowMapper.INSTANCE);
    }
}
